package com.qianya.system.face.config;


import cn.hutool.core.io.file.FileAppender;
import com.qianya.model.common.CommonResult;
import com.qianya.model.common.ResultCode;
import com.qianya.model.pojo.sys.qo.SysLogQO;
import com.qianya.system.face.util.SyslogUtil;
import com.qianya.system.face.web.patient.faceutil.rpc.BusinessException;
import com.qianya.system.face.web.patient.faceutil.rpc.Response;
import com.qianya.system.face.web.patient.feign.SystemManageFeign;
import com.qianya.util.BaseCommon;
import com.qianya.util.SystemConfig;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author: lhl
 * @Date: 2018/11/13 14:23
 */
@RestControllerAdvice
@Slf4j
@Component
public class GlobalExceptionHandler {
    @Resource
    private SystemManageFeign systemManageService;
    @Value("${spring.profiles.active}")
    private String actives;
    /**
     * @desc 自定义异常
     * @auther lhl
     */
    @ExceptionHandler(BusinessException.class)
    public Response businessException(BusinessException e) {
        log.error(e.getMessage(), e);
        Response response = new Response();
        response.setCode(e.getErrorCode().getCode());
        response.setMsg(e.getMsgCN());
        SysLogQO sysLogQO = new SysLogQO();
        sysLogQO.setResult("其他异常");
        SyslogUtil.insertSyslog(sysLogQO);
        systemManageService.save(sysLogQO);
        return response;
    }

    /**
     * 其他异常
     */
    @ExceptionHandler(Exception.class)
    public CommonResult handleException(Exception e) {
        if (actives.equals("dev")){
            log.error(e.getMessage());
        }else {
            File file=new File(SystemConfig.filePath()+File.separator+"system-manage"+File.separator+"logerr.txt");
            if (!file.exists()){
                try {
                    file.createNewFile();
                } catch (IOException ex) {
                    return CommonResult.error(ResultCode.ERROR,"系统异常");
                }
            }
            FileAppender fileAppender=new FileAppender(file,16,true);
            fileAppender.append(e.getMessage());
            fileAppender.flush();
            fileAppender.toString();
        }
        SysLogQO sysLogQO = new SysLogQO();
        if(e instanceof IndexOutOfBoundsException){
            sysLogQO.setResult("越界异常");
        }else if(e instanceof NullPointerException){
            sysLogQO.setResult("空指针异常");
        }else if(e instanceof RedisConnectionFailureException){
            sysLogQO.setResult("redis连接异常");
        } else if(e instanceof MyBatisSystemException){
            sysLogQO.setResult("msyql连接异常");
        } else if(e instanceof SQLException){
            sysLogQO.setResult("msyql操作异常");
        }else if(e instanceof FileNotFoundException){
            sysLogQO.setResult("文件未找到异常");
        }else if(e instanceof NumberFormatException){
            sysLogQO.setResult("类转换异常");
        }else if(e instanceof IOException){
            sysLogQO.setResult("IO异常");
        }else if(e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException meE=(MethodArgumentNotValidException)e;
            List<ObjectError> errorList = meE.getBindingResult().getAllErrors();
            StringBuffer sb = new StringBuffer();
            for (ObjectError objectError : errorList) {
                sb.append(objectError.getDefaultMessage() + ";");
            }
            sysLogQO.setResult("参数异常");
            SyslogUtil.insertSyslog(sysLogQO);

            systemManageService.save(sysLogQO);
            return CommonResult.error(ResultCode.ERROR,sb.toString());
        }else if (e instanceof ConstraintViolationException){
            ConstraintViolationException meE=(ConstraintViolationException)e;
            sysLogQO.setResult("参数异常");
            SyslogUtil.insertSyslog(sysLogQO);
            Set<ConstraintViolation<?>> obj=meE.getConstraintViolations();
            Iterator<ConstraintViolation<?>> it = obj.iterator();
            StringBuffer sb = new StringBuffer();
            while (it.hasNext()) {
                ConstraintViolation str = it.next();
                sb.append(str.getMessage() + ";");
            }
            systemManageService.save(sysLogQO);
            return CommonResult.error(ResultCode.ERROR,sb.toString());
        }else if(e instanceof BindException){
            BindException me = (BindException) e;
            List<ObjectError> errorList = me.getBindingResult().getAllErrors();
            StringBuffer sb = new StringBuffer();
            for (ObjectError objectError : errorList) {
                sb.append(objectError.getDefaultMessage() + ";");
            }
            return CommonResult.error(ResultCode.ERROR,sb.toString());
        }else {
            sysLogQO.setResult("系统异常");
        }
        SyslogUtil.insertSyslog(sysLogQO);
        systemManageService.save(sysLogQO);
        return CommonResult.error(ResultCode.ERROR,"系统异常");
    }


}
